import os
import argparse
import re
from pathlib import Path

def modify_gradle_properties(project_dir):
    """修改gradle.properties文件，添加阿里云镜像配置"""
    gradle_props_path = os.path.join(project_dir, 'gradle.properties')

    # 检查文件是否存在，不存在则创建
    if not os.path.exists(gradle_props_path):
        print(f"创建新的gradle.properties文件: {gradle_props_path}")
        with open(gradle_props_path, 'w') as f:
            pass

    # 读取文件内容
    with open(gradle_props_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 检查是否已存在镜像配置
    has_mirror_config = any('systemProp.http.proxyHost' in line for line in lines)

    if not has_mirror_config:
        # 添加镜像配置
        mirror_config = [
            '# 添加阿里云镜像配置\n',
            'systemProp.http.proxyHost=mirrors.aliyun.com\n',
            'systemProp.http.proxyPort=80\n',
            'systemProp.https.proxyHost=mirrors.aliyun.com\n',
            'systemProp.https.proxyPort=80\n'
        ]

        # 在文件开头插入配置
        lines = mirror_config + lines

        # 保存修改
        with open(gradle_props_path, 'w', encoding='utf-8') as f:
            f.writelines(lines)
        print(f"已更新gradle.properties: {gradle_props_path}")
    else:
        print(f"gradle.properties中已存在镜像配置，跳过修改")

def modify_build_file(file_path):
    """修改build.gradle或build.gradle.kts文件，替换仓库地址为阿里云镜像"""
    if not os.path.exists(file_path):
        print(f"错误: 未找到build文件: {file_path}")
        return

    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 检查是否已使用阿里云镜像
    if 'maven.aliyun.com' in content:
        print(f"{os.path.basename(file_path)}中已使用阿里云镜像，跳过修改")
        return

    is_kts = file_path.endswith('.kts')

    # 定义要替换的仓库配置和对应的阿里云镜像
    original_repos = {
        'mavenCentral\\(\\)': 'maven { url "https://maven.aliyun.com/repository/central" }',
        'jcenter\\(\\)': 'maven { url "https://maven.aliyun.com/repository/jcenter" }',
        'google\\(\\)': 'maven { url "https://maven.aliyun.com/repository/google" }'
    }

    # 根据文件类型调整语法
    if is_kts:
        for repo, replacement in original_repos.items():
            original_repos[repo] = replacement.replace('{ url ', '("').replace(' }', '")')

    # 替换仓库配置
    for repo_pattern, replacement in original_repos.items():
        content = re.sub(repo_pattern, replacement, content)

    # 添加阿里云Gradle插件仓库
    gradle_plugin_mirror = 'maven { url "https://maven.aliyun.com/repository/gradle-plugin" }'
    if is_kts:
        gradle_plugin_mirror = 'maven(url = "https://maven.aliyun.com/repository/gradle-plugin")'

    if gradle_plugin_mirror not in content:
        # 查找repositories块
        repo_pattern = r'repositories\s*\{|\s*repositories\s*\{|\s*repositories\s*\(\s*\)\s*\{|\s*repositories\s*\{\s*'
        match = re.search(repo_pattern, content)

        if match:
            # 在repositories块的开始位置添加阿里云Gradle插件仓库
            repo_block_start = match.end()
            content = content[:repo_block_start] + '\n        ' + gradle_plugin_mirror + content[repo_block_start:]

    # 保存修改
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"已更新{os.path.basename(file_path)}: {file_path}")

def modify_gradle_wrapper(project_dir):
    """修改gradle-wrapper.properties，替换Gradle下载链接为国内镜像"""
    wrapper_dir = os.path.join(project_dir, 'gradle', 'wrapper')
    wrapper_properties = os.path.join(wrapper_dir, 'gradle-wrapper.properties')

    if not os.path.exists(wrapper_properties):
        print(f"警告: 未找到Gradle wrapper配置文件: {wrapper_properties}")
        return

    with open(wrapper_properties, 'r', encoding='utf-8') as f:
        content = f.read()

    # 定义更灵活的URL匹配模式，支持转义的斜杠
    url_patterns = [
        r'distributionUrl\s*=\s*(https?:\\?/\\?/services\.gradle\.org/distributions/gradle-(\d+\.\d+)(-.*)?-bin\.zip)',
        r'distributionUrl\s*=\s*"([^"]+)"',  # 双引号包围的URL
        r'distributionUrl\s*=\s*\'([^\']+)\''  # 单引号包围的URL
    ]

    # 镜像URL模板
    mirror_templates = {
        'huawei': 'https://mirrors.huaweicloud.com/gradle/gradle-{version}{suffix}-bin.zip',
        'aliyun': 'https://maven.aliyun.com/repository/gradle-plugin/distributions/gradle-{version}{suffix}-bin.zip'
    }

    # 检查是否已使用国内镜像
    if any(mirror_domain in content for mirror_domain in ['huaweicloud.com', 'aliyun.com']):
        print(f"Gradle wrapper已使用国内镜像，跳过修改")
        return

    # 尝试匹配URL
    original_url = None
    version = None
    suffix = None

    for pattern in url_patterns:
        match = re.search(pattern, content)
        if match:
            original_url = match.group(1)
            if len(match.groups()) > 2:  # 捕获了版本和后缀
                version = match.group(2)
                suffix = match.group(3) or ''
            break

    if not original_url:
        print(f"未在{wrapper_properties}中找到distributionUrl配置")
        return

    if not version:
        # 尝试从URL中提取版本信息
        version_match = re.search(r'gradle-(\d+\.\d+)(-.*)?-bin\.zip', original_url)
        if version_match:
            version = version_match.group(1)
            suffix = version_match.group(2) or ''
        else:
            print(f"无法从URL中提取Gradle版本信息: {original_url}")
            return

    # 构建镜像URL
    mirror_url = mirror_templates['huawei'].format(version=version, suffix=suffix)

    # 处理转义斜杠
    escaped_original_url = original_url.replace('/', '\\/')

    # 替换URL，同时处理转义斜杠的情况
    new_content = re.sub(re.escape(escaped_original_url), mirror_url, content)
    if new_content == content:
        new_content = re.sub(re.escape(original_url), mirror_url, content)

    if new_content == content:
        print(f"警告: 替换失败，可能是正则表达式不匹配。请手动检查{wrapper_properties}")
        return

    with open(wrapper_properties, 'w', encoding='utf-8') as f:
        f.write(new_content)
    print(f"已更新Gradle wrapper下载地址为华为云镜像: {wrapper_properties}")

def main():
    parser = argparse.ArgumentParser(description='配置Gradle项目使用国内镜像')
    parser.add_argument('--project-dir', '-p', default='.', help='Gradle项目根目录')
    parser.add_argument('--mirror', '-m', default='huawei', choices=['huawei', 'aliyun'], help='指定国内镜像源')
    args = parser.parse_args()

    project_dir = os.path.abspath(args.project_dir)

    if not os.path.isdir(project_dir):
        print(f"错误: 指定的项目目录不存在: {project_dir}")
        return

    print(f"正在配置Gradle项目使用{args.mirror}镜像: {project_dir}")

    # 修改gradle.properties
    modify_gradle_properties(project_dir)

    # 修改build.gradle和build.gradle.kts
    build_gradle_path = os.path.join(project_dir, 'build.gradle')
    build_gradle_kts_path = os.path.join(project_dir, 'build.gradle.kts')

    if os.path.exists(build_gradle_path):
        modify_build_file(build_gradle_path)

    if os.path.exists(build_gradle_kts_path):
        modify_build_file(build_gradle_kts_path)

    # 检查settings.gradle(kts)文件
    settings_gradle_path = os.path.join(project_dir, 'settings.gradle')
    settings_gradle_kts_path = os.path.join(project_dir, 'settings.gradle.kts')

    if os.path.exists(settings_gradle_path):
        modify_build_file(settings_gradle_path)

    if os.path.exists(settings_gradle_kts_path):
        modify_build_file(settings_gradle_kts_path)

    # 修改Gradle wrapper配置
    modify_gradle_wrapper(project_dir)

    print("配置完成！现在你的Gradle项目将使用国内镜像加速依赖和Gradle下载。")

if __name__ == "__main__":
    main()
